//
//  ModuleOperationPlugin.m
//  Chamleon-template
//
//  Created by Fanty on 15/12/14.
//
//

#import "ModuleOperationPlugin.h"
#import "CubeModuleParser.h"
#import "DataCenter.h"
#import "Zilla.h"
#import "AsyncRequestWorkGroup.h"
#import "ZillaAccessData.h"
#import "AsyncRequestWorkGroup.h"
#import "CubeModuleManager.h"
#import "Modules.h"
#import "CApplication.h"

#import "IsolatedStorageFile.h"


#define APP_UPDATE      3

@interface ModuleOperationPlugin()<ZillaDelegate>
@end

@implementation ModuleOperationPlugin

-(void)pluginInitialize{
    [super pluginInitialize];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationUpdate:) name:@"CubeStatus" object:nil];

}

//获取所有模块列表
-(void)getAllModuleList:(CDVInvokedUrlCommand*)command{
    __block NSString *callbackId = command.callbackId;
    NSArray *serviceModules = [[DataCenter defaultCenter] allModules];
    
    if([serviceModules count]<1){     //要更新
        if(zillaSDK==nil){
            zillaSDK=[[Zilla alloc] initWithZillAccessData:[ZillaAccessData activeSession]];
            zillaSDK.delegate=self;
        }
        [zillaSDK cancelAllWorkGroup];
        
        AsyncRequestWorkGroup* workGroup=[zillaSDK syncModulesWithWorkGroup];
        __weak AsyncRequestWorkGroup* __task=workGroup;
        __weak ModuleOperationPlugin* plugin=self;
        [workGroup setFinishBlock:^{

            if([__task result]!=nil){
                [plugin syncModulesSuccess:[__task result]];
            }
            
            NSString* result=[CubeModuleParser parserJSONFromArray:[[DataCenter defaultCenter] allModules]];
           

            CDVPluginResult*pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result];
          
            [plugin.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
            callbackId=nil;
        }];
    }
    else{
        
        NSString* result=[CubeModuleParser parserJSONFromArray:serviceModules];
        CDVPluginResult*pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
        
     }

}

-(void)getInstalledModuleList:(CDVInvokedUrlCommand*)command{

    @autoreleasepool {
        NSString* callbackId=command.callbackId;
        NSArray* models = [DataCenter defaultCenter].installMoudules;
        
        NSString* result=[CubeModuleParser parserJSONFromArray:models];
        CDVPluginResult*pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
    }
}



-(void)getUninstallModuleList:(CDVInvokedUrlCommand*)command{

    __block NSString* callbackId=command.callbackId;
    
    NSArray* models = [DataCenter defaultCenter].serviceModules;
    if([models count]<1){     //要更新
        if(zillaSDK==nil){
            zillaSDK=[[Zilla alloc] initWithZillAccessData:[ZillaAccessData activeSession]];
            zillaSDK.delegate=self;
        }
        [zillaSDK cancelAllWorkGroup];
        
        AsyncRequestWorkGroup* workGroup=[zillaSDK syncModulesWithWorkGroup];
        __weak AsyncRequestWorkGroup* __task=workGroup;
        __weak ModuleOperationPlugin* plugin=self;
        [workGroup setFinishBlock:^{
            
            
            if([__task result]!=nil){
                [plugin syncModulesSuccess:[__task result]];
            }
             NSString* result=[CubeModuleParser parserJSONFromArray:[[DataCenter defaultCenter] uninstallModules]];
            CDVPluginResult*pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result];
            [plugin.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
            callbackId=nil;

        }];
        
    }
    else{
        
        NSString* result=[CubeModuleParser parserJSONFromArray:[[DataCenter defaultCenter] uninstallModules]];

        CDVPluginResult*pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
        
    }
}

-(void)getUpgradeableModuleList:(CDVInvokedUrlCommand*)command{
    __block NSString* callbackId=command.callbackId;
    

    if(zillaSDK==nil){
        zillaSDK=[[Zilla alloc] initWithZillAccessData:[ZillaAccessData activeSession]];
        zillaSDK.delegate=self;
    }
    [zillaSDK cancelAllWorkGroup];
    
    AsyncRequestWorkGroup* workGroup=[zillaSDK syncModulesWithWorkGroup];
    __weak AsyncRequestWorkGroup* __task=workGroup;
    __weak ModuleOperationPlugin* plugin=self;
    [workGroup setFinishBlock:^{
        
        if([__task result]!=nil){
            [plugin syncModulesSuccess:[__task result]];
            
        }
        NSString* result=[CubeModuleParser parserJSONFromArray:[[DataCenter defaultCenter] updatableModules]];
        CDVPluginResult*pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result];
        [plugin.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
        callbackId=nil;
        
    }];
}

-(void)installModule:(CDVInvokedUrlCommand*)command{
    NSString* _callbackId = command.callbackId;
    
    NSString* identifier =  [[command.arguments objectAtIndex:0] lowercaseString];
    
    [[CApplication sharedApplication].cubeModuleManager installModule:identifier];
    
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@""];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];

}

-(void)upgradeModule:(CDVInvokedUrlCommand*)command{
    NSString* _callbackId = command.callbackId;
    
    NSString* identifier =  [[command.arguments objectAtIndex:0] lowercaseString];
    
    [[CApplication sharedApplication].cubeModuleManager updateModule:identifier];
    
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@""];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];

}

-(void)getModuleDetail:(CDVInvokedUrlCommand*)command{
    NSString* _callbackId = command.callbackId;
    
    NSString* identifier =  [[command.arguments objectAtIndex:0] lowercaseString];

    CubeModel* cubeModel=[[DataCenter defaultCenter] finidInstallCubeModule:identifier];
    if(cubeModel==nil){
        cubeModel=[[DataCenter defaultCenter] finidServiceCubeModule:identifier];
    }
    NSString* result=[CubeModuleParser serialize:cubeModel];
    
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];

}


-(void)deleteModule:(CDVInvokedUrlCommand*)command{
    NSString* _callbackId = command.callbackId;
    
    NSString* identifier =  [[command.arguments objectAtIndex:0] lowercaseString];
    
    [[CApplication sharedApplication].cubeModuleManager uninstallModule:identifier];
    
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@""];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];

}

-(void)checkAppUpdate:(CDVInvokedUrlCommand*)command{
    __block NSString* _callbackId = command.callbackId;

    if(zillaSDK==nil){
        zillaSDK=[[Zilla alloc] initWithZillAccessData:[ZillaAccessData activeSession]];
        zillaSDK.delegate=self;
    }
    AsyncRequestWorkGroup* workGroup=[zillaSDK checkAppVersionWithWorkGroup];
    
    __weak AsyncRequestWorkGroup* __task=workGroup;
    __weak ModuleOperationPlugin* plugin=self;
    [workGroup setFinishBlock:^{
        
        
        if([__task result]!=nil){
            [plugin syncVersionFinish:[__task result]];
        }
        CDVPluginResult*pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@""];
        [plugin.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];
        
    }];
}

-(void)syncModulesSuccess:(CubeModelList*)remoteServiceList{
    
    modelList=remoteServiceList;
    
    
    DataCenter* dataCenter=[DataCenter defaultCenter];
    
    //本地的service模块全部替换成最新模块
    if([modelList.modules count]>0){
        dataCenter.serviceModules = modelList.modules;
        [[CApplication sharedApplication].cubeModuleManager syncModuleList:modelList.modules];
    }
}

-(void)syncVersionFinish:(CubeModelList*)remoteServiceList{
    
    modelList=remoteServiceList;
    int newBuild = modelList.build;
    int currentBuild = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] intValue];
    if (newBuild > currentBuild){
        NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
        NSString *message = [NSString stringWithFormat:@"当前版本:%@\n最新版本:%@\n版本说明:\n%@", currentVersion, modelList.version, [modelList.releaseNote length]>0?modelList.releaseNote:@""];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[ NSString stringWithFormat:@"%@平台版本更新",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"] ] message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
        alertView.tag=APP_UPDATE;
        [alertView show];
    }
}


-(void)notificationUpdate:(NSNotification*)notification{
    NSDictionary* dict=notification.object;
    if([dict isKindOfClass:[NSDictionary class]]){
        NSString* type=[dict objectForKey:@"type"];
        NSString* identifier=[dict objectForKey:@"identifier"];
        if([type isEqualToString:@"install"]){
        }
        else if([type isEqualToString:@"success"]){
            [self.commandDelegate evalJs:[NSString stringWithFormat:@"moduleInstallState('%@','true')",identifier]];
        }
        
        else if([type isEqualToString:@"failed"]){
            [self.commandDelegate evalJs:[NSString stringWithFormat:@"moduleInstallState('%@','false')",identifier]];
            
        }
        else if([type isEqualToString:@"process"]){
            NSNumber* number=[dict objectForKey:@"count"];
            [self.commandDelegate evalJs:[NSString stringWithFormat:@"updateModuleProgress('%@',%@)",identifier,number]];
            
        }
        
    }
}


#pragma mark alertview delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag==APP_UPDATE){
        if(buttonIndex==1){
            //版本更新
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:modelList.appUrl]];
        }
        else{
        }
    }
}

@end

@implementation ModuleOperationDelegate

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [[CApplication sharedApplication].cubeModuleManager loadLocalModuleList];
    return YES;
}

@end